//
//  BPChoosePicViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/1/13.
//  Copyright © 2017年 cesh. All rights reserved.
//

#import "BPChoosePicViewController.h"
#import "BPPreviewViewController.h"
#import <UIImageView+WebCache.h>

@interface BPChoosePicViewController () <UICollectionViewDelegate, UICollectionViewDataSource, XLPhotoBrowserDatasource>

@property (weak, nonatomic) IBOutlet UIButton *comfirmBtn;
//图片的list
@property (strong, nonatomic) NSArray *picList;
//最多可选
@property (assign, nonatomic) NSInteger maxSelect;
//超过最多可选的单价
@property (assign, nonatomic) double overMaxPrice;
//保存所有cell右上角的选中按钮
@property (strong, nonatomic) NSMutableArray <UIButton *> *selectedBtns;

//保存所有图片的imgV
@property (strong, nonatomic) NSMutableArray *picViews;
@property (weak, nonatomic) IBOutlet UILabel *maxSelectLbl;
@property (weak, nonatomic) IBOutlet UILabel *numberOfSelectedLbl;

@end

@implementation BPChoosePicViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (NSMutableArray *)picViews {
    if (_picViews == nil) {
        _picViews = [NSMutableArray array];
    }
    return _picViews;
}

- (NSMutableArray *)selectedBtns {
    if (_selectedBtns == nil) {
        _selectedBtns = [NSMutableArray array];
    }
    return _selectedBtns;
}

- (NSMutableArray *)selectedPicIndex {
    if (_selectedPicIndex == nil) {
        _selectedPicIndex = [NSMutableArray array];
    }
    return _selectedPicIndex;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选片入册";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"预览" style:UIBarButtonItemStylePlain target:nil action:nil];
    _comfirmBtn.layer.cornerRadius = 4.0;
    [self getData];
}

- (void)getData {
    [SVProgressHUD showWithStatus:@"读取中..."];
    NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    [mgr POST:[NSString stringWithFormat:@"%@?c=Order&&a=canSelectImg",requestURL]
   parameters:@{@"token" : user[@"token"],
                @"orderID" : self.orderID,
                @"page" : @"1",
                @"pagesize" : @"100"
                }
     progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
             NSLog(@"选片 %@", responseObject);
             [SVProgressHUD dismiss];
             self.picList = responseObject[@"data"][@"list"];
             self.maxSelect = [responseObject[@"data"][@"maxSelect"] integerValue];
             self.overMaxPrice = [responseObject[@"data"][@"overMaxPrice"] doubleValue];
             
             self.maxSelectLbl.text = responseObject[@"data"][@"maxSelect"];
             //图片选择的collectionView
             CGFloat collectionPadding = 4;
             // 创建流水布局
             UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
             // 行间距
             flowLayout.minimumLineSpacing = collectionPadding;
             // 每个item 之间的间距
             flowLayout.minimumInteritemSpacing = collectionPadding;
             
             // 设置每个cell 的尺寸
             CGFloat cellWH = (screenW - 3 * collectionPadding) * 0.25;
             flowLayout.itemSize = CGSizeMake(cellWH, cellWH);
             
             // 设置滚动方向
             flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
             
             UICollectionView *collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, screenW, screenH - 60 - 64) collectionViewLayout:flowLayout];
             collectionV.backgroundColor = [UIColor clearColor];
             [self.view addSubview:collectionV];
             [collectionV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"choosePicCell"];
             collectionV.delegate = self;
             collectionV.dataSource = self;
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
     }];
}

#pragma mark - collection view datasource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"choosePicCell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UICollectionViewCell alloc]init];
    }
    
    UIImageView *picView = [[UIImageView alloc]init];
    [picView sd_setImageWithURL:[NSURL URLWithString:self.picList[indexPath.row][@"url"]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    cell.backgroundView = picView;
    [self.picViews addObject:picView];
    //给cell的右上角添加一个标志选中与否的按钮
    UIButton *selected = [[UIButton alloc]initWithFrame:CGRectMake(cell.frame.size.width * 0.8 - 5, 5, cell.frame.size.width * 0.2, cell.frame.size.width * 0.2)];
    [selected addTarget:self action:@selector(selectedBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [selected setContentMode:UIViewContentModeCenter];
    [selected setBackgroundImage:[UIImage imageNamed:@"oval_n"] forState:UIControlStateNormal];
    [selected setBackgroundImage:[UIImage imageNamed:@"oval_s"] forState:UIControlStateSelected];
    //给每一个button设置一个tag
    
    selected.tag = indexPath.row + 1;
    [self.selectedBtns addObject:selected];
    [cell.contentView addSubview:selected];
    return cell;
}

- (void)selectButtonAtIndex:(NSUInteger)index {
    //根据index取得按钮
    UIButton *selectedBtn = [[UIButton alloc]init];
    for (UIButton *button in self.selectedBtns) {
        if (index == button.tag) {
            selectedBtn = button;
        }
    }
    [self selectedBtnClick:selectedBtn];
}

- (void)selectedBtnClick:(UIButton *)selected {
    selected.selected = !selected.selected;
    //如果选中，则添加进数组，数字加一
    if(selected.selected) {
        [self.selectedPicIndex addObject:@(selected.tag)];
        [selected setTitle:[NSString stringWithFormat:@"%lu", (unsigned long)self.selectedPicIndex.count] forState:UIControlStateSelected];
        [selected.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
        [selected setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    }
    //如果取消选中， 则从数组中剔除，重新设置所有图片右上角的数字
    else {
        [self.selectedPicIndex removeObject:@(selected.tag)];
        //遍历所有当前已选中的button
        NSInteger i = 1;
        for (UIButton *seletedBtn in self.selectedBtns) {
            if (seletedBtn.selected) {
                [seletedBtn setTitle:[NSString stringWithFormat:@"%lu", i++] forState:UIControlStateSelected];
                [seletedBtn.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
                [seletedBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            }
        }
    }
    self.numberOfSelectedLbl.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.selectedPicIndex.count];
    //根据选择张数是否大于可选，设置按钮的文字
    if (self.selectedPicIndex.count > self.maxSelect) {
        [self.comfirmBtn setTitle:[NSString stringWithFormat:@"支付 %lu * %.2f", self.selectedPicIndex.count - self.maxSelect, self.overMaxPrice] forState:UIControlStateNormal];
    }
    else {
        [self.comfirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    }
    NSLog(@"%@", self.selectedPicIndex);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.picList.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

#pragma mark - collection view delegate
//点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithCurrentImageIndex:indexPath.row imageCount:self.picList.count datasource:self];
    browser.selectedPicIndex = self.selectedPicIndex;
    browser.browserStyle = XLPhotoBrowserStyleSimple;
    browser.choosePicVC = self;
}

#pragma mark    -   XLPhotoBrowserDatasource

- (UIImage *)photoBrowser:(XLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    UIImageView *img = self.picViews[index];
    return img.image;
}

- (UIView *)photoBrowser:(XLPhotoBrowser *)browser sourceImageViewForIndex:(NSInteger)index
{
    return self.picViews[index];
}
//确认选片按钮
- (IBAction)confirmChoosePic:(UIButton *)sender {
    //拦截选择张数不够的情况
    if (self.selectedPicIndex.count < self.maxSelect) {
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"您还需要选择%li张", self.maxSelect - self.selectedPicIndex.count]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    //获取选择图片的id
    NSMutableArray *picIDs =[NSMutableArray array];
    for (NSNumber *index in self.selectedPicIndex) {
        NSInteger i = [index integerValue] - 1;
        [picIDs addObject:self.picList[i][@"id"]];
    }
    NSLog(@"选择图片的id%@", picIDs);
    
    //上传选择的片
    [SVProgressHUD showWithStatus:@"读取中..."];
    NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    [mgr POST:[NSString stringWithFormat:@"%@?c=Order&&a=saveSelectImg",requestURL]
   parameters:@{@"token" : user[@"token"],
                @"imgs" : picIDs
                }
     progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [SVProgressHUD dismiss];
         NSLog(@"上传图片%@",responseObject);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
     }];
    
}

@end
